//
//  LocationViewController.m
//  Tencent_Map_Demo_Raster
//
//  Created by WangXiaokun on 16/1/12.
//  Copyright © 2016年 WangXiaokun. All rights reserved.
//

#import "MapLocationViewController.h"
#import "SRActionSheet.h"
#import "PowerBelongViewController.h"
#import "AddShopViewController.h"
#import "NewAddShopViewController.h"

@interface MapLocationViewController () <QMapViewDelegate>

{
}

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) ShopModel *smodel;

@property (nonatomic,strong) MBProgressHUD *hub;
@end

@implementation MapLocationViewController

- (void)initView {
    
    if (!_mapView) {
        CGFloat windowWidth = self.view.bounds.size.width;
        CGFloat windowHeight = self.view.bounds.size.height;
        _mapView = [[QMapView alloc] initWithFrame:CGRectMake(0,
                                                              0,
                                                              windowWidth,
                                                              windowHeight- 64)];
        _mapView.delegate = self;
        [self.view addSubview:_mapView];
        _mapView.showsUserLocation = YES;
        
        _mapView.userTrackingMode = QUserTrackingModeFollow;
        
        _mapView.showsScale = YES;
        
    }
    
    [_mapView removeAnnotations:_mapView.annotations];
    
    for (ShopModel *model in _dataArray) {
        
        //定义pointAnnotation
        QPointAnnotation *point = [[QPointAnnotation alloc] init];
        point.title = model.name;
        
        point.subtitle = model.status.integerValue == 0 ? @"待铺设" : @"已铺设";
    
        CLLocationDegrees latitude = model.latitude.doubleValue;
        
        CLLocationDegrees longitude = model.longitude.doubleValue;

        
        point.coordinate = CLLocationCoordinate2DMake(latitude
                                                      ,longitude);
                //向mapview添加annotation
        [_mapView addAnnotation:point];
    }
    
}

-(void)mapView:(QMapView *)mapView didUpdateUserLocation:(QUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    NSLog(@"coordinate:%f,%f, heading:%f", userLocation.coordinate.latitude, userLocation.coordinate.longitude, userLocation.heading.trueHeading);
}


//- (void)mapView:(QMapView *)mapView annotationView:(QAnnotationView *)view didChangeDragState:(QAnnotationViewDragState)newState fromOldState:(QAnnotationViewDragState)oldState{
//    NSLog(@"移动了 位置为- > %f,%f,",view.annotation.coordinate.latitude,view.annotation.coordinate.longitude);
//}

-(QAnnotationView *)mapView:(QMapView *)mapView
          viewForAnnotation:(id<QAnnotation>)annotation {
    static NSString *pointReuseIndentifier = @"pointReuseIdentifier";
    
    if ([annotation isKindOfClass:[QPointAnnotation class]]) {
        //添加默认pinAnnotation
        
        QPinAnnotationView *annotationView = (QPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[QPinAnnotationView alloc]
                              initWithAnnotation:annotation
                              reuseIdentifier:pointReuseIndentifier];
        }
        //显示气泡，默认NO
        annotationView.canShowCallout = YES;
        //设置大头针颜色
        annotationView.pinColor = QPinAnnotationColorGreen;
        //添加左侧信息窗附件
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:[UIImage imageNamed:@"gaidong"] forState:UIControlStateNormal];
        btn.frame = CGRectMake(0, 0, 25, 25);
        btn.titleLabel.text = annotation.title;
        [btn addTarget:self action:@selector(jumpTipButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        annotationView.leftCalloutAccessoryView = btn;
        //可以拖动
        annotationView.draggable = NO;
        //自定义annotation图标
        
        if ([annotation.subtitle isEqualToString:@"已铺设"]) {
            UIImage *image1 = [UIImage imageNamed:@"yipushe"];
            annotationView.image = image1;
        }else{
            UIImage *image1 = [UIImage imageNamed:@"weipushe"];
            annotationView.image = image1;
        }
        
        return annotationView;
    }
    return nil;
}


- (void)mapViewWillStartLocatingUser:(QMapView *)mapView
{
    //获取开始定位的状态
}

- (void)mapViewDidStopLocatingUser:(QMapView *)mapView
{
    //获取停止定位的状态
}

#pragma mark - Life Circle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self initView];
    _dataArray = [NSMutableArray array];
    [self loadMapShopInfo];
    [self getNoti];
}

- (void)getNoti{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadMapShopInfo) name:@"loadMap" object:nil];
}

- (void)loadMapShopInfo{
//    NSLog(@"访问");
    [[AFClient shareInstance] getShopSimpleListByEid:kUserId page_size:@"1000" page_index:@"0" status:nil progressBlock:nil success:^(id responseBody) {
        if ([responseBody[@"code"] integerValue] == 200) {
            [_dataArray removeAllObjects];
            for (NSDictionary *dic in responseBody[@"data"]) {
                ShopModel *model = [[ShopModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [_dataArray addObject:model];
            }
            [self initView];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        
    }];
}

- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)jumpTipButtonClick:(UIButton *)button{
    NSLog(@"%@",button.titleLabel.text);
    
    for (ShopModel *model in _dataArray) {
        if ([model.name isEqualToString:button.titleLabel.text]) {
            _smodel = model;
            break;
        }
    }
    
    SRActionSheet *actionSheet ;
    if (_smodel.status.integerValue == 1) {
        actionSheet = [SRActionSheet sr_actionSheetViewWithTitle:nil
                                                     cancelTitle:@"取消"
                                                destructiveTitle:nil
                                                     otherTitles:@[@"所属充电宝", @"编辑门店", @"已铺设", @"删除"]
                                                     otherImages:nil
                                               selectActionBlock:^(SRActionSheet *actionSheet, NSInteger index) {
                                                   NSLog(@"%zd", index);
                                                   if (index == 0) {
                                                       [self powerBelongFunByShopId:_smodel];
                                                   }else if (index == 1){
                                                       [self editShopInfoFun:_smodel];
                                                   }else if (index == 2){
                                                       if (_smodel.all_num.integerValue == 0) {
                                                           [self waitingSettedFunByShopId:_smodel.id];
                                                       }else{
                                                           UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"该店铺下还有充电宝未撤回，无法设置" message:nil preferredStyle:UIAlertControllerStyleAlert];
                                                           UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                                               
                                                           }];
                                                           [alert addAction:action];
                                                           [self presentViewController:alert animated:YES completion:nil];
                                                       }
                                                   }else{
                                                       [self deleteFunByShopId:_smodel.id];
                                                   }
                                               }];
    }else{
        actionSheet = [SRActionSheet sr_actionSheetViewWithTitle:nil
                                                     cancelTitle:@"取消"
                                                destructiveTitle:nil
                                                     otherTitles:@[@"所属充电宝", @"编辑门店", @"已铺设", @"删除"]
                                                     otherImages:nil
                                               selectActionBlock:^(SRActionSheet *actionSheet, NSInteger index) {
                                                   NSLog(@"%zd", index);
                                                   if (index == 0) {
                                                       [self powerBelongFunByShopId:_smodel];
                                                   }else if (index == 1){
                                                       [self editShopInfoFun:_smodel];
                                                   }else if (index == 2){
                                                       [self hasSettedFunByShopId:_smodel.id];
                                                   }else{
                                                       [self deleteFunByShopId:_smodel.id];
                                                   }
                                               }];
    }
    
    [actionSheet show];

}

#pragma mark - actionSheet功能

#pragma mark - 所属充电宝
- (void)powerBelongFunByShopId:(ShopModel *)model{
    UIStoryboard *storyoboard = kMainStroyboard;
    PowerBelongViewController *powerBelongVC = [storyoboard instantiateViewControllerWithIdentifier:@"PowerBelongViewController"];
    powerBelongVC.model = model;
    [self.navigationController pushViewController:powerBelongVC animated:YES];
}

#pragma mark - 编辑门店

- (void)editShopInfoFun:(ShopModel *)model{
    UIStoryboard *storyboard = kMainStroyboard;
    NewAddShopViewController *addShopVC = [storyboard instantiateViewControllerWithIdentifier:@"NewAddShopViewController"];
    addShopVC.jumpType = @"1";

    addShopVC.model = model;
    [self.navigationController pushViewController:addShopVC animated:YES];
}

#pragma mark - 已铺设

- (void)hasSettedFunByShopId:(NSString *)shopId{
//    kAlert(@"已铺设");
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] setToHasUsedById:shopId eid:kUserId progressBlock:nil success:^(id responseBody) {
        if ([responseBody[@"code"] integerValue] == 200) {
            [self.hub hideAnimated:YES];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"铺设成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self loadMapShopInfo];
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)waitingSettedFunByShopId:(NSString *)shopId{
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] waitToHasUsedById:shopId eid:kUserId progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"该店铺已变更为待铺设" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self loadMapShopInfo];
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}


#pragma mark - 删除
- (void)deleteFunByShopId:(NSString *)shopId{
//    kAlert(@"删除");
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认要删除吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.hub hideAnimated:YES];
        
        self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        // Set the label text.
        self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
        [[AFClient shareInstance] deleteShopById:shopId eid:kUserId progressBlock:nil success:^(id responseBody) {
            if ([responseBody[@"code"] integerValue] == 200) {
                [self.hub hideAnimated:YES];
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"删除成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self loadMapShopInfo];
                }];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                kAlert(responseBody[@"message"]);
            }
        } failure:^(NSError *error) {
            [self.hub hideAnimated:YES];
        }];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action2];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
